package com.tiger.cloud.controller.crm;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.tiger.cloud.common.mybatis.BaseController;
import com.tiger.cloud.model.crm.AppVersion;
import com.tiger.cloud.service.crm.IAppVersionService;
import com.tiger.cloud.util.Objects;
import com.tiger.cloud.util.Response;
import com.tiger.cloud.util.ResponseUtil;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * app版本控制
 */
@Controller
@RequestMapping(value = "appVersion")
@Api(value = "APP版本",tags = "版本")
public class AppVersionController extends BaseController {

	private static final Logger logger=Logger.getLogger(AppVersionController.class);
	
	@Autowired
	private IAppVersionService appVersionService;
	
	/**
	 * 查找最新版本的APP
	 * @return
	 */
	@RequestMapping(value = "findNewVersion", method = RequestMethod.POST)
	@ResponseBody
	@ApiOperation(value = "查找最新版本的APP",notes = "")
	public Response findNewVersion(){
		AppVersion appVersion=new AppVersion();
		appVersion.setOrderBy("last_update_date desc");
		AppVersion datas=appVersionService.findOne(appVersion);
		return ResponseUtil.ok(datas);
	}
	
	/**
	 * APK文件下载
	 * @param request
	 * @param response
	 * @param filename
	 * @throws IOException
	 */
	@RequestMapping(value = "/app_download/{filename}")
	@ApiOperation(value = "下载apk文件",notes = "")
	public void downloadApp(HttpServletRequest request, HttpServletResponse response, @PathVariable("filename") String filename) throws IOException {
		String fileSufix = "zhizaozhushou";
		Boolean targetDownload = null;
		System.out.println("filename[" + filename + "]");
		String apkPath = request.getSession().getServletContext().getRealPath("/static") + File.separator + "apk";
		File apkFile = new File(apkPath);
		String[] filenames = apkFile.list();
		if (StringUtils.isNotEmpty(filename) && filenames != null) {
			filename = filename + ".apk";
			for (String apkFilename : filenames) {
				if (apkFilename.equals(filename)) {
					targetDownload = true;
				}
			}
		} else {
			List<Float> vs_ = new ArrayList<Float>();
			for (String string : filenames) {
				String v_ = string.substring(string.indexOf('_') + 1, string.lastIndexOf('.'));
				float _v =Objects.strToFloat(v_, -1);
				if (_v > -1) {
					vs_.add(_v);
				}
			}
			Collections.sort(vs_);
			filename = fileSufix + "_" + vs_.get((vs_.size() - 1)) + ".apk";
			targetDownload = false;
		}
		if (targetDownload != null) {
			File downloadFile = new File(apkPath, filename);
			try {
				response.setContentType("application/vnd.android.package-archive");
				response.setHeader("Content-Length", String.valueOf(downloadFile.length()));
				response.setHeader("content-transfer-encoding", "binary");
				response.setHeader("Content-Disposition", "attachment; filename=" + filename);
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(FileUtils.readFileToByteArray(downloadFile));
				outputStream.close();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
}